<template>
  <div class="home-page" ref="homePage">
    <div class="pc">
      <img class="img_video" :src="images.start" @click="openVideo" />
      <img class="img_aotu" :src="images.aotu" @click="aotuImgClick" />
      <div class="home-bottom">
        <img class="home-bottom-left" :src="images.bottom_left" />
        <img class="home-bottom-right" :src="images.bottom_right" />
      </div>
    </div>

    <div class="mobile">
      <img class="img_video" :src="images.m_start" @click="openVideo" />
      <img class="img_aotu" :src="images.m_aotu" @click="aotuImgClick" />
      <div class="home-bottom">
        <img class="home-bottom-left" :src="images.m_bottom_left" />
        <img class="home-bottom-right" :src="images.m_bottom_right" />
      </div>
    </div>

    <d-mask
      :isShowMask="isShowMask"
      :canCloseByClickMask="canCloseByClickMask"
      @handleShowMask="showMask"
      @handleCloseMask="closeMask"
    >
      <div class="mask-box" v-show="isShowMask">
        <div class="mask-title">
          <img :src="images.close" alt="close" @click="closeMask" />
        </div>

        <div class="mask-content">
          <div class="m-content-progress">
            <div class="m-c-progress-bar">
              <div ref="progressBarFull" class="m-c-progress-bar-full"></div>
            </div>

            <div class="m-c-progress-desc">
              <span class="color-yellow">5036</span>
              <span class="color-grey">/</span>8888
            </div>
          </div>

          <div class="m-c-content-title">Minted</div>

          <div class="m-content-counter">
            <div class="m-c-counter-left" @click="decreaseClick">
              <img :src="images.decrease" />
            </div>
            <div class="m-c-counter-center">{{ buyNum }}</div>
            <div class="m-c-counter-right" @click="increaseClick">
              <img :src="images.increase" />
            </div>
          </div>

          <div class="m-content-price">
            <div class="m-c-price-font">Mining cost</div>

            <div class="m-c-price-calc">0.10ETH</div>
          </div>

          <div id="connectButton" class="m-content-btn enableEthereumButton">
            {{ buttonTips }}
          </div>
        </div>
      </div>
    </d-mask>

    <div class="videoMask" v-if="isShowVideo">
      <div
        class="video-container"
        v-if="isShowVideo"
        @click="showClose"
        @mouseenter="showClose"
        @touchstart="showClose"
      >
        <transition name="fade">
          <img
            v-show="isShowClose"
            class="video-close"
            @click="closeVideo"
            src="@/assets/images/icons/close.png"
          />
        </transition>

        <video
          ref="vo"
          muted
          class="fillWidth"
          :autoplay="videolist.autoplay"
          :controls="videolist.controls"
          webkit-playsinline="true"
          playsinline="true"
          @ended="handleVideoEnd"
          @pause="handleVideoPause"
          @play="handleVideoPlay"
          @click="showClose"
          @touchstart="showClose"
        >
          <!-- x-webkit-airplay="true"
        x5-video-player-type="h5"
        x5-video-player-fullscreen="true"
        x5-video-ignore-metadata="true"
        @play="handleFullScreen"
        @fullscreenchange="handleFullscreenchange" -->
          <source src="@/assets/media/video.mp4" type="video/mp4" />
          <!-- <source src="@/assets/media/video.mp4" type="video/webm" /> -->
        </video>
      </div>
    </div>
  </div>
</template>

<script>
// --- components ---
import DMask from "@/components/DMask.vue";

// --- utils ---
import MetaMask from "@/utils/metamask.js";
import { setCookie, clearCookies, getCookie } from "@/utils/cookie";
import { isPhone } from "../../utils";

// --- others ---
import MetaMaskOnboarding from "@metamask/onboarding";
const currentUrl = new URL(window.location.href);
const forwarderOrigin =
  currentUrl.hostname === "localhost" ? "http://localhost:9010" : undefined;

export default {
  name: "HomePage",
  components: { DMask },
  data() {
    return {
      // static
      images: {
        aotu: require("@/assets/images/home/home_aotunft.png"),
        start: require("@/assets/images/home/home_video_start.png"),
        bottom_left: require("@/assets/images/home/home_bottom_left.png"),
        bottom_right: require("@/assets/images/home/home_bottom_right.png"),
        m_aotu: require("@/assets/images/home/m_home_aotunft.png"),
        m_start: require("@/assets/images/home/m_home_video_start.png"),
        m_bottom_left: require("@/assets/images/home/m_home_bottom_left.png"),
        m_bottom_right: require("@/assets/images/home/m_home_bottom_right.png"),
        close: require("@/assets/images/icons/icon_close.png"),
        increase: require("@/assets/images/icons/icon_increase.png"),
        decrease: require("@/assets/images/icons/icon_decrease.png"),
      },
      // flag
      isShowVideo: false,
      isShowMask: false,
      canCloseByClickMask: true,
      isPhone: false,
      isShowClose: false,
      isPause: false,
      // progress
      totalNum: 8888,
      remainderNum: 5036,
      // buy count
      buyNum: 1,
      // price
      eth: 0.1,
      // mint
      canContented: false,
      buttonTips: "MINT",
      isConnect: false,
      account: "",
      // video
      videolist: {
        autoplay: true,
        controls: "controls",
      },
      // video timer
      timer: null,
    };
  },
  computed: {
    // calc the
    progressFullCpt() {
      // Less than one percent, then calculate by one percent
      let res = (this.remainderNum / this.totalNum) * 100;
      res = res > 1 ? res : 1;
      return Math.floor(res) + "%";
    },
  },
  watch: {
    // if mask dialog shows, the progress's animation is going to run
    isShowMask(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          setTimeout(() => {
            // this.$refs.homePage.parentNode.parentNode.children[0].style.pointerEvents = "none"
            this.$refs.homePage.style["z-index"] = 10;
            this.$refs.progressBarFull.style.width = this.progressFullCpt;
          }, 100);

          // this.initialize();
          // this.checkLogin();
        });
      } else {
        setTimeout(() => {
          // this.$refs.homePage.parentNode.parentNode.children[0].style.pointerEvents = ""
          this.$refs.homePage.style["z-index"] = 8;
        }, 300);
      }
    },
    // if close btn is showing, timer is running to close the btn with 3s
    isShowClose(newVal) {
      setTimeout(() => {
        if (newVal) {
          if (!this.isPause) {
            this.timer = setTimeout(() => {
              this.isShowClose = false;
            }, 3000);
          }
        }
      }, 0);
    },
    isPause(newVal) {
      setTimeout(() => {
        if (!newVal) {
          this.timer = setTimeout(() => {
            this.isShowClose = false;
          }, 3000);
        } else {
          if (this.timer) {
            clearTimeout(this.timer);
          }
        }
      }, 0);
    },
    isShowVideo(newVal) {
      newVal ? this.stopScroll() : this.startScroll();
    },
  },
  methods: {
    // ========== async ==========
    async getNonce(address) {
      this.isConnect = true;
      let top = address.slice(0, 4);
      let bottom = address.substring(address.length - 4, address.length);
      this.account = top + "...." + bottom;
      this.canContented = false;
      localStorage.setItem("isLogin", JSON.stringify(true));
      setCookie("token", address);
      setCookie("publicAddress", address);
      // let count = await MetaMask.getGmsNFTBlanace();
      // if (count > 0) {
      //   localStorage.setItem("isMember", JSON.stringify(true));
      // }
    },
    async linkMetaMask() {
      // const newAccounts = await ethereum.request({
      //   method: "eth_requestAccounts",
      // });
    },
    async initialize() {
      let that = this;
      const onboardButton = document.getElementById("connectButton");
      let state = await MetaMask.init();
      if (state === 0) {
        this.buttonTips = "Install MetaMask!";
        onboardButton.addEventListener("click", () => {
          that.buttonTips = "Onboarding in progress";
          that.canContented = false;
          const onboarding = new MetaMaskOnboarding({ forwarderOrigin });
          onboarding.startOnboarding();
          onboardButton.disabled = true;
        });
      } else if (state === 1) {
        this.getAccount();
        this.buttonTips = "Mint";
        onboardButton.addEventListener("click", () => {
          MetaMask.connect()
            .then((res) => {
              console.log(res);
              that.getNonce(res[0]);
            })
            .catch((err) => {
              console.log(err);
            });
        });
      }
    },
    async getAccount() {
      let that = this;
      ethereum.on("accountsChanged", function (accounts) {
        if (accounts && accounts.length > 0) {
          that.getNonce(accounts[0]);
        } else {
          that.buttonTips = "Connect Wallet";
          that.isConnect = false;
          clearCookies();
          localStorage.clear();
        }
      });
    },
    checkLogin() {
      let publicAddress = getCookie("publicAddress");
      if (publicAddress) {
        this.getNonce(publicAddress);
      }
    },

    // ========== common Fn ==========
    // open aotu dialog
    aotuImgClick() {
      this.showMask();
    },

    // ========== mask dialog ==========
    // show the mask
    showMask() {
      if (isPhone()) {
        this.$toast({
          className: "toastStyle",
          icon: "star",
          type: "text",
          message: "COMING SOON",
          duration: 2000,
          closeOnClick: true,
          closeOnClickOverlay: true,
        });
      } else {
        this.$message({
          customClass: "msgStyle",
          iconClass: "el-icon-star-on",
          type: "warning",
          message: "COMING SOON",
          duration: 2000,
        });
      }

      // this.isShowMask = true;
    },
    // close the mask
    closeMask() {
      this.isShowMask = false;
    },
    // increase buyNum (+1)
    increaseClick() {
      if (this.buyNum >= this.remainderNum) return;
      this.buyNum++;
    },
    // decrease buyNum (-1)
    decreaseClick() {
      if (this.buyNum <= 1) return;
      this.buyNum--;
    },
    // increase buyNum to max
    buyNumToMaxClick() {
      this.buyNum = this.remainderNum;
    },
    // buyNum input blur
    buyNumBlur() {
      if (this.buyNum <= 1) {
        this.buyNum = 1;
      } else if (this.buyNum >= this.remainderNum) {
        this.buyNum = this.remainderNum;
      }
    },

    // ========== video ==========
    // show close btn
    showClose() {
      this.isShowClose = true;
    },
    hiddenClose() {
      this.isShowClose = false;
    },
    // open video
    openVideo() {
      this.isShowVideo = true;
      this.$nextTick(() => {
        // this.$children[0].$refs.videoPlayer.player.play();
        this.$refs.vo.play();
      });
    },
    // close video
    closeVideo() {
      this.isShowVideo = false;
    },
    // video end
    handleVideoEnd() {
      this.closeVideo();
    },
    // video pause
    handleVideoPause() {
      this.isPause = true;
      this.showClose();
    },
    // video start
    handleVideoPlay() {
      // this.hiddenClose();
      this.isPause = false;
    },
    // handleFullScreen(e) {
    //   this.launchFullscreen(e.target);
    // },
    // launchFullscreen(element) {
    //   if (element.requestFullscreen) {
    //     element.requestFullscreen();
    //   } else if (element.mozRequestFullScreen) {
    //     element.mozRequestFullScreen();
    //   } else if (element.msRequestFullscreen) {
    //     element.msRequestFullscreen();
    //   } else if (element.oRequestFullscreen) {
    //     element.oRequestFullscreen();
    //   } else if (element.webkitRequestFullscreen) {
    //     element.webkitRequestFullScreen();
    //   } else {
    //     var docHtml = document.documentElement;
    //     var docBody = document.body;
    //     var videobox = element;
    //     var cssText = "width:100%;height:100%;overflow:hidden;";
    //     docHtml.style.cssText = cssText;
    //     docBody.style.cssText = cssText;
    //     videobox.style.cssText = cssText + ";" + "margin:0px;padding:0px;";
    //   }
    // },
    // handleExitFullScreen(e) {
    //   this.exitFullscreen(e.target);
    // },
    // exitFullscreen(element) {
    //   if (document.exitFullscreen) {
    //     document.exitFullscreen();
    //   } else if (document.msExitFullscreen) {
    //     document.msExitFullscreen();
    //   } else if (document.mozCancelFullScreen) {
    //     document.mozCancelFullScreen();
    //   } else if (document.oRequestFullscreen) {
    //     document.oCancelFullScreen();
    //   } else if (document.webkitExitFullscreen) {
    //     document.webkitExitFullscreen();
    //   } else {
    //     var docHtml = document.documentElement;
    //     var docBody = document.body;
    //     var videobox = element;
    //     docHtml.style.cssText = "";
    //     docBody.style.cssText = "";
    //     videobox.style.cssText = "";
    //     document.IsFullScreen = false;
    //   }
    // },
    // handleFullscreenchange() {
    //   if (!this.checkIsFullScreen()) {
    //     this.closeVideo();
    //   }
    // },
    // checkIsFullScreen() {
    //   var isFullScreen =
    //     document.fullscreen ||
    //     document.mozFullScreen ||
    //     document.webkitIsFullScreen;
    //   return isFullScreen == undefined ? false : isFullScreen;
    // },
    // add stop scroll event
    stopScroll() {
      this.$nextTick(() => {
        this.$refs.homePage.parentNode.parentNode.children[0].style.pointerEvents =
          "none";
        this.$refs.homePage.parentNode.parentNode.children[0].style.opacity = 0.1;
      });
      document.body.scrollIntoView(true);
      document.body.style.overflow = "hidden";
      document.addEventListener("touchmove", this.bodyScroll, {
        passive: false,
      });
    },
    // remove stop scroll event
    startScroll() {
      this.$nextTick(() => {
        this.$refs.homePage.parentNode.parentNode.children[0].style.pointerEvents =
          "";
        this.$refs.homePage.parentNode.parentNode.children[0].style.opacity = 1;
      });
      document.body.style.overflow = "";
      document.removeEventListener("touchmove", this.bodyScroll, {
        passive: false,
      });
    },
  },
  mounted() {
    isPhone() ? (this.isPhone = true) : (this.isPhone = false);
  },
};
</script>

<style lang="less" scoped>
.home-page {
  position: relative;
  width: 100%;
  height: 1080px;
  background-image: url("~@/assets/images/home/home_background.png");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
  z-index: 8;

  .mobile {
    display: none;
  }

  .pc {
    .img_video {
      position: absolute;
      bottom: 495px;
      left: 50%;
      transform: translateX(-50%);
      width: 90px;
      cursor: pointer;
    }

    .img_aotu {
      position: absolute;
      bottom: 68px;
      left: 50%;
      transform: translateX(-50%);
      width: 809px;
      cursor: pointer;
    }

    .home-bottom {
      display: flex;
      position: absolute;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);

      .home-bottom-left {
        width: 16px;
      }
      .home-bottom-right {
        width: 55px;
        margin-left: 5px;
      }
    }
  }

  .videoMask {
    position: absolute;
    width: 100%;
    height: 100%;
    min-height: 2160px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.9);
    z-index: 99;
  }

  // video
  .video-container {
    position: relative;
    left: 50%;
    top: 150px;
    transform: translateX(-50%);
    // height: 1080px;
    width: 1258px;
    overflow: hidden;
    .fillWidth {
      width: 100%;
      height: auto;
      object-fit: fill;
      // object-fit: cover;
    }

    .video-close {
      position: absolute;
      top: 10px;
      right: 10px;
      width: 15px;
      height: 15px;
      z-index: 9;
      cursor: pointer;
    }
  }

  .mask-box {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 735px;
    height: 514px;
    background-image: url("~@/assets/images/mint/mint_background.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    box-sizing: border-box;
    padding-right: 20px;
    overflow: hidden;
    user-select: none;

    .mask-title {
      margin-top: 20px;
      font-size: 0;

      img {
        display: block;
        width: 15px;
        cursor: pointer;
      }
    }

    .mask-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 385px;
      height: 390px;
      background: #ffffff;
      backdrop-filter: blur(10px);
      box-sizing: border-box;
      padding: 0 25px;
      margin-top: 52px;
      overflow: hidden;

      .m-content-progress {
        width: 100%;
        margin-top: 72px;
        .m-c-progress-bar {
          position: relative;
          width: 100%;
          height: 14px;
          background: #e5e5e5;

          .m-c-progress-bar-full {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 0;
            background: linear-gradient(90deg, #3dc1ff 0%, #0055ff 100%);
            transition: all 1s ease;
          }
        }

        .m-c-progress-desc {
          display: flex;
          justify-content: center;
          margin-top: 10px;
          font-size: 16px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #32abf0;
          line-height: 16px;
        }
      }

      .m-c-content-title {
        font-size: 18px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #222222;
        line-height: 16px;
        margin-top: 10px;
      }

      .m-content-counter {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 50px;
        background: #ffffff;
        box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        border: 1px solid #dddddd;
        margin-top: 20px;
        box-sizing: border-box;
        padding: 0 5px;

        .m-c-counter-left,
        .m-c-counter-right {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 40px;
          height: 40px;
          background: linear-gradient(90deg, #3dc1ff 0%, #0055ff 100%);
          font-size: 0;
          border-radius: 4px;
          cursor: pointer;

          img {
            display: block;
            width: 16px;
          }
        }

        .m-c-counter-center {
          font-size: 20px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #222222;
          line-height: 20px;
        }
      }

      .m-content-price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 54px;
        background: #333333;
        box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        border: 1px solid #dddddd;
        box-sizing: border-box;
        padding: 0 20px;
        margin-top: 20px;

        .m-c-price-font,
        .m-c-price-calc {
          font-size: 16px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #ffffff;
          line-height: 16px;
        }
      }

      .m-content-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 65px;
        background-image: url("~@/assets/images/mint/mint_confirm_btn.png");
        background-repeat: no-repeat;
        background-size: 100% 100%;
        background-position: center center;
        font-size: 20px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #ffffff;
        line-height: 20px;
        margin-top: 20px;
        cursor: pointer;
      }
    }
  }

  // public colors
  .color-yellow {
    color: #f48301 !important;
  }
  .color-grey {
    color: #aaaaaa !important;
  }
  .opacity-half {
    opacity: 0.5 !important;
  }
}

@media screen and (max-width: 768px) {
  .home-page {
    position: relative;
    height: 102.4vw;
    background-image: url("~@/assets/images/home/m_home_background.png");
    margin-top: 16vw;

    .pc {
      display: none;
    }

    .mobile {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      align-items: center;

      .img_video {
        width: 13.3333vw;
        margin-bottom: 10.6667vw;
      }
      .img_aotu {
        width: 78.9333vw;
        margin-bottom: 3.2vw;
      }
      .home-bottom {
        display: flex;
        margin-bottom: 2.6667vw;

        .home-bottom-left {
          width: 3.2vw;
        }
        .home-bottom-right {
          width: 11.2vw;
        }
      }
    }

    .mask-box {
      width: 92vw;
      height: 175.2vw;
      overflow: auto;
      background-image: url("~@/assets/images/mint/m_mint_background.png");
      padding: 0 4vw;

      .mask-title {
        margin-top: 46.6667vw;
        font-size: 0;

        img {
          display: block;
          width: 4vw;
          cursor: pointer;
        }
      }

      .mask-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        height: auto;
        background: none;
        backdrop-filter: blur(10px);
        box-sizing: border-box;
        padding: 0 4vw;
        margin-top: 34.9333vw;
        overflow: hidden;

        .m-content-progress {
          width: 100%;
          margin-top: 0;
          .m-c-progress-bar {
            position: relative;
            width: 100%;
            height: 3.7333vw;
            background: #e5e5e5;
          }

          .m-c-progress-desc {
            display: flex;
            justify-content: center;
            font-size: 4.2667vw;
            font-family: PingFangSC-Semibold, PingFang SC;
            font-weight: 600;
            color: #222222;
            line-height: 4.2667vw;
            margin-top: 2.6667vw;
          }
        }

        .m-c-content-title {
          font-size: 4.2667vw;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #222222;
          line-height: 4.2667vw;
          margin-top: 2.6667vw;
        }

        .m-content-counter {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 13.3333vw;
          background: #ffffff;
          box-shadow: 0px 0px 2.6667vw 0px rgba(0, 0, 0, 0.1);
          border-radius: 1.0667vw;
          border: 0.2667vw solid #dddddd;
          margin-top: 5.3333vw;
          box-sizing: border-box;
          padding: 0 1.3333vw;

          .m-c-counter-left,
          .m-c-counter-right {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 10.6667vw;
            height: 10.6667vw;
            background: linear-gradient(90deg, #3dc1ff 0%, #0055ff 100%);
            font-size: 0;
            border-radius: 0.5333vw;
            cursor: pointer;

            img {
              display: block;
              width: 4.2667vw;
            }
          }

          .m-c-counter-center {
            font-size: 4.8vw;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #222222;
            line-height: 4.8vw;
          }
        }

        .m-content-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 14.4vw;
          background: #333333;
          box-shadow: 0px 0px 2.6667vw 0px rgba(0, 0, 0, 0.1);
          border-radius: 1.0667vw;
          border: 0.2667vw solid #dddddd;
          box-sizing: border-box;
          padding: 0 4vw;
          margin-top: 5.3333vw;

          .m-c-price-font,
          .m-c-price-calc {
            font-size: 3.7333vw;
            font-family: PingFangSC-Semibold, PingFang SC;
            font-weight: 600;
            color: #ffffff;
            line-height: 3.7333vw;
          }
        }

        .m-content-btn {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 17.3333vw;
          background-image: url("~@/assets/images/mint/mint_confirm_btn.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
          background-position: center center;
          font-size: 5.3333vw;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #ffffff;
          line-height: 5.3333vw;
          margin-top: 5.3333vw;
          cursor: pointer;
        }
      }
    }

    .videoMask {
      height: 100vh;
      min-height: 288vw;
    }

    .video-container {
      position: absolute;
      left: 0;
      top: 51.2vw;
      transform: translateY(-50%);
      width: 100%;
      height: auto;
      // overflow: unset;

      .fillWidth {
        width: 100%;
        height: 100%;
        // object-fit: cover;
      }

      .video-close {
        position: absolute;
        top: 1.3333vw;
        right: 1.3333vw;
        width: 3.3333vw;
        height: 3.3333vw;
        z-index: 99;
        transition: all 0.5s ease;
      }
    }
  }
}

// public animation
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
